package com.mall.order.service.impl;

import com.mall.api.order.dto.OrderDTO;
import com.mall.api.order.dto.OrderItemDTO;
import com.mall.api.product.ProductFeignClient;
import com.mall.api.product.dto.ProductDTO;
import com.mall.common.exception.BusinessException;
import com.mall.order.entity.Order;
import com.mall.order.entity.OrderItem;
import com.mall.order.mapper.OrderItemMapper;
import com.mall.order.mapper.OrderMapper;
import com.mall.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ProductFeignClient productFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO createOrder(OrderDTO orderDTO) {
        // 创建订单
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setStatus(0);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.insert(order);

        // 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (OrderItemDTO itemDTO : orderDTO.getItems()) {
            // 检查商品库存
            ProductDTO productDTO = productFeignClient.getProductById(itemDTO.getProductId()).getData();
            if (productDTO == null) {
                throw new BusinessException("商品不存在");
            }
            if (productDTO.getStock() < itemDTO.getQuantity()) {
                throw new BusinessException("商品库存不足");
            }

            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(itemDTO.getProductId());
            orderItem.setQuantity(itemDTO.getQuantity());
            orderItem.setPrice(itemDTO.getPrice());
            orderItem.setCreateTime(LocalDateTime.now());
            orderItem.setUpdateTime(LocalDateTime.now());
            orderItemMapper.insert(orderItem);
            orderItems.add(orderItem);

            // 更新商品库存
            productFeignClient.updateStock(itemDTO.getProductId(), productDTO.getStock() - itemDTO.getQuantity());
        }

        return convertToDTO(order, orderItems);
    }

    @Override
    public OrderDTO getOrderById(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        List<OrderItem> orderItems = orderItemMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, id));

        return convertToDTO(order, orderItems);
    }

    @Override
    public OrderDTO getOrderByUserId(Long userId) {
        Order order = orderMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Order>()
                        .eq(Order::getUserId, userId));
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        List<OrderItem> orderItems = orderItemMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, order.getId()));

        return convertToDTO(order, orderItems);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(Long id, Integer status) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        order.setStatus(status);
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrder(Long id) {
        if (orderMapper.deleteById(id) == 0) {
            throw new BusinessException("订单不存在");
        }
        orderItemMapper.delete(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, id));
    }

    private OrderDTO convertToDTO(Order order, List<OrderItem> orderItems) {
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(order, orderDTO);

        List<OrderItemDTO> itemDTOs = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            OrderItemDTO itemDTO = new OrderItemDTO();
            BeanUtils.copyProperties(orderItem, itemDTO);
            itemDTOs.add(itemDTO);
        }
        orderDTO.setItems(itemDTOs);

        return orderDTO;
    }
} 